import { createPage } from '@mpxjs/core';
import { DetailOfCustomEvent } from "../../utils/typies";
import {albumSorts, getAlbums, hotKeys, searchSong} from "../../services/recommend.service";
import {searchHistoryKey} from "../../utils/consts";
import {AlbumBrief, HotKeyVo, SongItem} from "../../services/types";
import {numberFormat} from "../../utils/tools";

interface Album {
  sortId: number;
  sortName: string;
  list: AlbumBrief[];
}

interface RecommendSearchVo {
  data: {
    showSearchPanel: boolean;
    searchValue: string;
    hotKeys: HotKeyVo[];
    search: (value: string) => void;
    searchResult: SongItem[];
    searchHistories: string[];
    url: string;
    albums: Album[];
  }
}

// @ts-ignore
createPage<RecommendSearchVo['data']>({
  data: {
    search: () => {},
    hotKeys: [],
    searchResult: [],
    searchHistories: [],
    searchValue: '',
    showSearchPanel: false,
    url: 'http://p.qpic.cn/music_cover/C0ScLIodTrpFjicullL2wzK7BXzibCz8cKrsP3ZhlEr0GxyX5aiagl50A/600?n=1',
    albums: []
  },
  onLoad() {
    this.getHistory();
    this.getAlbums();
  },
  tabChange(event: any) {
    console.log('tab change', event);
  },
  handleSearch(event: DetailOfCustomEvent<string>): void {
    this.searchValue = event.detail;
    if (this.searchValue) {
      wx.setStorageSync(searchHistoryKey, this.searchHistories.concat(this.searchValue));
      searchSong(this.searchValue).then(res => {
        this.searchResult = res || [];
        if (!this.searchResult.length) {
          wx.showToast({
            title: '没有结果',
            icon: 'none'
          });
        }
      });
    } else {
      wx.showToast({
        title: '请输入搜索词',
        icon: 'error'
      });
    }
  },
  handleClear(): void {
    this.searchValue = '';
    this.searchResult = [];
    this.getHistory();
  },
  async searchPanelActiveChange(event: DetailOfCustomEvent<boolean>) {
    if (!this.hotKeys.length) {
      this.hotKeys = await hotKeys();
    }
    this.showSearchPanel = event.detail;
    this.handleClear();
  },
  getHistory(): void {
    this.searchHistories = wx.getStorageSync(searchHistoryKey) || [];
  },
  getAlbums(): void {
    const sorts = albumSorts();
    if (sorts.length) {
      sorts.forEach(async item => {
        const list = await getAlbums(item.id);
        this.albums.push({
          sortId: item.id,
          sortName: item.name,
          list: list.map(lItem => ({ ...lItem, listennumStr: numberFormat(lItem.listennum) }))
        });
      });
      // console.log('albums', this.albums);
    }
  },
  toList(event: DetailOfCustomEvent<AlbumBrief>): void {
    wx.navigateTo({
      url: '/pages/song-list/index',
      success({ eventChannel }) {
        eventChannel.emit('albumBriefFromRecommend', event.detail);
      }
    });
  }
});
